package jp.co.apl.haven_enquete.android.dao;

import java.util.Date;
import java.util.List;
import java.util.Map;

import jp.co.apl.haven.generated.HavenProtos.Answer;
import jp.co.apl.haven_enquete.android.db.DatabaseHelper;
import jp.dev7.android.util.Contexts;
import jp.dev7.android.util.Dbs;
import jp.dev7.android.util.Dbs.FuncCur;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.google.common.base.Function;
import com.google.common.collect.Maps;

public class AnswerDataDao {

    private static final String TABLE_NAME = "ANSWER";

    private final Context context;
    private final DatabaseHelper helper;

    public AnswerDataDao(Context context) {
        this.context = context;
        helper = new DatabaseHelper(context);
    }

    public List<Answer> findAll() {
        SQLiteDatabase db = helper.getReadableDatabase();
        try {
            return Dbs.loadAsList(db, TABLE_NAME, new FuncCur<Answer>() {
                @Override
                public Answer apply(Integer id, String value, Date updateAt) {
                    Answer answer =
                        Answer
                            .newBuilder()
                            .setTerminalId(Contexts.getAndroidId(context))
                            .setQuistionId(id)
                            .setAnswer(value)
                            .setAnsweredDate(updateAt.getTime())
                            .build();
                    Log.d("haven", "create answer " + answer);
                    return answer;
                }
            });
        } finally {
            db.close();
        }
    }

    public Map<Integer, Answer> loadAsMap() {
        return Maps.uniqueIndex(findAll(), new Function<Answer, Integer>() {
            @Override
            public Integer apply(Answer input) {
                return input.getQuistionId();
            }
        });
    }

    public void save(int id, String value) {
        Log.i("haven", "save answer id = " + id + ", value = " + value);
        SQLiteDatabase db = helper.getWritableDatabase();
        try {
            Dbs.save(db, TABLE_NAME, id, value);
        } finally {
            db.close();
        }
    }

}
